using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using CSP.MembershipInterface.ObjectModel;
using Microsoft.SharePoint;

namespace CSP.WebParts
{
    public class CSPSatisfactionSurvey : BaseWebPart
    {
        DropDownList ddlChoices;
        Button btnSubmit;
        Label lblIntro;
        HiddenField hdnID;
        Case _incident = null;
        string ticketnumber = string.Empty;
        bool error = false;

        //private CSPLib.CrmFacade facade;
        //private CSPLib.CrmFacade Facade
        //{
        //    get
        //    {
        //        if (facade == null)
        //        {
        //            facade = new CSPLib.CrmFacade("lrgserver");
        //        }
        //        return facade;
        //    }
        //}

        CSP.MembershipInterface.MembershipServiceClient client = null;

        ///// <summary>
        ///// Loads the data stored in the data source
        ///// </summary>
        //private void BindData()
        //{
        //    SPSecurity.RunWithElevatedPrivileges(delegate()
        //    {
        //        CSP.MembershipInterface.MembershipServiceClient client = null;

        //        try
        //        {
        //            client = new CSP.MembershipInterface.MembershipServiceClient();
        //            caseTypes = client.GetCaseTypes();
        //            client.Close();
        //        }
        //        catch (Exception ex)
        //        {
        //            this.LogMessage(this.LoadResource(WebPartConstants.CSPProceduresLoadErrorMessage), this.GetType().Name, ex);
        //            throw new CSP.Core.CSPException(ex);
        //        }
        //        finally
        //        {
        //            if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
        //                client.Close();
        //        }
        //    });

        //}

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            try
            {

                if (Page.Request.QueryString["ticketnumber"] == null)
                {
                    lblIntro = new Label();
                    lblIntro.Text = "Notification: you can't access this page because you need your case ticket number.";
                    this.Controls.Add(lblIntro);
                    error = true;
                    return;
                }

                ticketnumber = Page.Request.QueryString["ticketnumber"].ToString();
                
                client = new CSP.MembershipInterface.MembershipServiceClient();
                _incident = client.GetCaseByCaseID(ticketnumber);
                string username = Context.User.Identity.Name;
                Citizen _contact = client.GetCitizenByUsername(username);
                client.Close();


                // TODO: check it by adding a service
                //if (_incident.customersatisfactioncode != null)
                //{
                //    lblIntro = new Label();
                //    lblIntro.Text = "Notification: This case been already rated.";
                //    this.Controls.Add(lblIntro);
                //    error = true;
                //    return;
                //}


               
                //if (_incident.customerid.Value != _contact.contactid.Value)
                //{
                //    lblIntro = new Label();
                //    lblIntro.Text = "Notification: you don't have rights to access this information.";
                //    this.Controls.Add(lblIntro);
                //    error = true;
                //    return;

                //}
                hdnID = new HiddenField();
                hdnID.Value = ticketnumber;
                this.Controls.Add(hdnID);
                lblIntro = new Label();
                if (Page.IsPostBack)
                {
                    lblIntro.Text = "Thanks for sending us your feedback";
                }
                else
                {
                    lblIntro.Text = "Please submit this information and help us to improve citizen care services.";
                }
                this.Controls.Add(lblIntro);

                ddlChoices = new DropDownList();
                ddlChoices.Items.Add(new ListItem("Very dissatisfied", "1"));
                ddlChoices.Items.Add(new ListItem("Dissatisfied", "2"));
                ListItem li = new ListItem("Neutral", "3");
                li.Selected = true;
                ddlChoices.Items.Add(li);
                ddlChoices.Items.Add(new ListItem("Satisfied", "4"));
                ddlChoices.Items.Add(new ListItem("Very satisfied", "5"));

                this.Controls.Add(ddlChoices);

                this.btnSubmit = new Button();
                btnSubmit.Text = "Submit my oppinion";
                btnSubmit.Click += new EventHandler(btnSubmit_Click);
                this.Controls.Add(btnSubmit);

            }
            catch (Exception ex)
            {
                lblIntro = new Label();
                lblIntro.Text = ex.Message;
                this.Controls.Add(lblIntro);
                error = true;
            }
        }

        void btnSubmit_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                CSP.MembershipInterface.MembershipServiceClient client = null;

                try
                {
                    client = new CSP.MembershipInterface.MembershipServiceClient();
                    client.UpdateCaseSatisfaction(ticketnumber, Convert.ToInt16(ddlChoices.SelectedValue));
                    client.Close();
                }
                catch (Exception ex)
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPProceduresLoadErrorMessage), this.GetType().Name, ex);
                    throw new CSP.Core.CSPException(ex);
                }
                finally
                {
                    if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                        client.Close();
                }
            });
        }



        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            writer.Write("<table width='100%'><tr><td>");
            lblIntro.RenderControl(writer);
            if (!Page.IsPostBack && !error)
            {
                writer.Write("</td></tr><tr><td>");

                StringBuilder caseDetails = new StringBuilder();
                caseDetails.Append("<hr/><p><b>Case details:</b><br/>");
                if (_incident == null)
                {
                    caseDetails.Append("<p>Incident is null</p>");
                }
                caseDetails.AppendFormat("Ticket number: {0}<br/>", ticketnumber);
                if (_incident.Type != null)
                {
                    caseDetails.AppendFormat("Case type: {0}<br/>", _incident.Type.CaseTypeTitle);
                }
                if (_incident.CreatedDate != null)
                {
                    caseDetails.AppendFormat("Date: {0}<br/></p><hr/>", _incident.CreatedDate.ToLongDateString());
                }
                writer.Write(caseDetails.ToString());
                writer.Write("</td></tr><tr><td>");
                ddlChoices.RenderControl(writer);
                writer.Write("</td></tr><tr><td>");
                btnSubmit.RenderControl(writer);
            }
            writer.Write("</td></tr></table>");
        }
    }
}
